import multiprocessing as mp
import os
import json
import time
from typing import List, Dict, Any, Optional
from queue import Empty
import traceback

class VideoProcessManager:
    """视频处理进程管理器"""
    
    def __init__(self):
        self.process_pool = None
        self.max_workers = 5
        self.task_queue = None
        self.result_queue = None
        self.processes = []
        self.running = False
    
    def start(self, max_workers: int = 5):
        """启动进程池"""
        if self.running:
            return
        
        self.max_workers = max_workers
        self.task_queue = mp.Queue()
        self.result_queue = mp.Queue()
        
        # 启动工作进程
        for i in range(max_workers):
            process = mp.Process(
                target=self._worker_process,
                args=(self.task_queue, self.result_queue, i)
            )
            process.start()
            self.processes.append(process)
        
        self.running = True
        print(f"启动 {max_workers} 个处理进程")
    
    def stop(self):
        """停止进程池"""
        if not self.running:
            return
        
        self.running = False
        
        # 发送停止信号
        for _ in self.processes:
            self.task_queue.put(None)
        
        # 等待进程结束
        for process in self.processes:
            process.join(timeout=5)
            if process.is_alive():
                process.terminate()
                process.join()
        
        self.processes.clear()
        print("所有处理进程已停止")
    
    def submit_task(self, task_data: Dict[str, Any]):
        """提交处理任务"""
        if not self.running:
            raise RuntimeError("进程池未启动")
        
        self.task_queue.put(task_data)
    
    def get_result(self, timeout: float = 0.1) -> Optional[Dict[str, Any]]:
        """获取处理结果"""
        try:
            return self.result_queue.get(timeout=timeout)
        except Empty:
            return None
    
    @staticmethod
    def _worker_process(task_queue, result_queue, worker_id):
        """工作进程函数"""
        from .video_processor import VideoProcessor
        from .file_manager import FileManager
        
        processor = VideoProcessor()
        file_manager = FileManager()
        
        print(f"[进程{worker_id+1}] 工作进程启动")
        
        while True:
            try:
                # 获取任务
                task = task_queue.get()
                if task is None:  # 停止信号
                    break
                
                task_type = task.get('type')
                file_path = task.get('file_path')
                output_folder = task.get('output_folder')
                target_resolution = task.get('target_resolution', '原分辨率')
                save_audio = task.get('save_audio', True)
                save_video = task.get('save_video', True)
                save_subtitles = task.get('save_subtitles', False)
                remove_subtitles = task.get('remove_subtitles', False)
                remove_hardcoded_subtitles = task.get('remove_hardcoded_subtitles', False)
                
                if task_type == 'process_video':
                    # 处理视频任务
                    try:
                        start_time = time.time()
                        
                        # 发送开始处理状态
                        result_queue.put({
                            'type': 'file_start',
                            'file_path': file_path,
                            'worker_id': worker_id,
                            'timestamp': start_time
                        })
                        
                        # 处理视频
                        result = processor.process_video(
                            file_path, output_folder, file_manager, target_resolution,
                            save_audio, save_video, save_subtitles,
                            remove_subtitles, remove_hardcoded_subtitles
                        )
                        
                        end_time = time.time()
                        duration = end_time - start_time
                        
                        # 发送完成状态
                        result_queue.put({
                            'type': 'file_complete',
                            'file_path': file_path,
                            'worker_id': worker_id,
                            'success': result['success'],
                            'error': '; '.join(result['errors']) if result['errors'] else None,
                            'duration': duration,
                            'timestamp': end_time
                        })
                        
                    except Exception as e:
                        # 发送错误状态
                        result_queue.put({
                            'type': 'file_complete',
                            'file_path': file_path,
                            'worker_id': worker_id,
                            'success': False,
                            'error': str(e),
                            'duration': 0,
                            'timestamp': time.time()
                        })
                
                elif task_type == 'parse_video':
                    # 解析视频信息任务
                    try:
                        start_time = time.time()
                        
                        # 发送开始解析状态
                        result_queue.put({
                            'type': 'parse_start',
                            'file_path': file_path,
                            'worker_id': worker_id,
                            'timestamp': start_time
                        })
                        
                        # 解析视频信息
                        video_info = processor.get_video_info(file_path)
                        file_size = os.path.getsize(file_path)
                        
                        result = {
                            'path': file_path,
                            'size': file_size,
                            'duration': video_info['duration'],
                            'resolution': f"{video_info['video_width']}x{video_info['video_height']}",
                            'fps': video_info['fps'],
                            'video_codec': video_info['video_codec'],
                            'audio_codec': video_info['audio_codec'],
                            'has_audio': video_info['has_audio']
                        }
                        
                        end_time = time.time()
                        duration = end_time - start_time
                        
                        # 发送解析完成状态
                        result_queue.put({
                            'type': 'parse_complete',
                            'file_path': file_path,
                            'worker_id': worker_id,
                            'success': True,
                            'result': result,
                            'duration': duration,
                            'timestamp': end_time
                        })
                        
                    except Exception as e:
                        # 发送解析错误状态
                        result_queue.put({
                            'type': 'parse_complete',
                            'file_path': file_path,
                            'worker_id': worker_id,
                            'success': False,
                            'error': str(e),
                            'duration': 0,
                            'timestamp': time.time()
                        })
                
            except Exception as e:
                print(f"[进程{worker_id+1}] 处理任务时出错: {e}")
                traceback.print_exc()
        
        print(f"[进程{worker_id+1}] 工作进程退出")
    
    def get_process_status(self) -> Dict[str, Any]:
        """获取进程状态"""
        if not self.running:
            return {'running': False, 'process_count': 0}
        
        alive_count = sum(1 for p in self.processes if p.is_alive())
        return {
            'running': self.running,
            'process_count': len(self.processes),
            'alive_count': alive_count,
            'queue_size': self.task_queue.qsize() if self.task_queue else 0
        } 